package com.winspread.ui.fragment

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager

/**
 *Author: Amin
 *Data: 2022/4/9 14:37
 *
 *Description:
 *
 */
class ScrollControlViewPager : ViewPager {

    // 是否可以滑动切换
    var isSlide = true

    // 是否scrollview嵌套 因嵌套界面出现不显示的情况
    var isScroll = false
        set(value) {
            field = value
            invalidate()
        }

    constructor(context: Context?) : super(context!!)
    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!,
        attrs
    )


    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return isSlide && super.onInterceptTouchEvent(ev)
    }

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        return isSlide && super.onTouchEvent(ev)
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var heightMeasureSpec = heightMeasureSpec
        if (isScroll) {
            var height = 0
            for (i in 0 until childCount) {
                val childAt = getChildAt(i)
                childAt.measure(
                    widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
                )
                val h = childAt.measuredHeight
                if (h > height) height = h
            }
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }


}